// pages/taxi/taxi.ts
// @ts-ignore
import { getDistant, getDistantAndMoney, GetRangeMoney, obtainVehicleType } from '../../../http/api/positionApi'
// @ts-ignore
import Toast from 'tdesign-miniprogram/toast/index'
import { createOrder, payOrder } from '../../../http/api/orderService'
import { formatTime, throttle } from '../../../utils/util'

const tokenMixin = require('../../../mixin/tokenMixin')
const imageCdn = 'https://tdesign.gtimg.com/miniprogram/images'
const swiperList = [
    {
        value: `${imageCdn}/swiper1.png`,
        ariaLabel: '图片1'
    },
    {
        value: `${imageCdn}/swiper2.png`,
        ariaLabel: '图片2'
    },
    {
        value: `${imageCdn}/swiper1.png`,
        ariaLabel: '图片1'
    },
    {
        value: `${imageCdn}/swiper2.png`,
        ariaLabel: '图片2'
    }
]
Page({
    behaviors: [tokenMixin],
    /**
     * 页面的初始数据
     */
    data: {
        swiperList,
        // 公告栏
        marquee1: {
            speed: 80,
            loop: -1,
            delay: 0
        },
        datetimeVisible: false,
        dialogVisible: false,
        moneyVisible: false, // 费用
        datetime: new Date().getTime(),
        active: 0,
        carType: [],
        drivingTime: '请选择用车时间',
        info: '约-km',
        distance: '约-km',
        duration: '',
        startTime: new Date().getTime(),
        startPoint: null,
        endPoint: null,
        flowingNum: 0, // 跟车人数
        flowingPet: 1, // 宠物数量
        coupon: '', // 优惠劵
        couponInfo: {}, // 优惠劵信息
        showCoupon: false,
        moneyInfo: {}, // 订单费用信息
        oldMoney: 0,
        remark: '' // 备注信息
    } as any,

    onRemarkInput(e: any) {
        this.setData({
            remark: e.detail.value
        })
    },

    onMoneyChange() {
        this.setData({ moneyVisible: true })
    },

    onMoneyVisibleChange(e: any) {
        this.setData({
            moneyVisible: e.detail.visible
        })
    },

    toPreferentialCenter() {
        wx.navigateTo({
            url: `/pages/my/preferentialCenter/preferentialCenter?type=1&all_money=${this.data.oldMoney}`
        })
    },

    verify() {
        const { startPoint, endPoint, drivingTime }: any = this.data

        if (startPoint == null || endPoint == null) {
            Toast({
                context: this,
                selector: '#t-toast',
                message: '请选择地址',
                theme: 'error',
                direction: 'column'
            })
            return false
        } else if (drivingTime === '请选择用车时间') {
            Toast({
                context: this,
                selector: '#t-toast',
                message: '请选择用车时间',
                theme: 'error',
                direction: 'column'
            })
            return false
        }
        return true
    },

    buy: throttle(async function (this: any) {
        const { flowingNum, flowingPet, startPoint, endPoint, active, drivingTime, carType, couponInfo, moneyInfo, remark }: any = this.data
        console.log(flowingNum, flowingPet, startPoint, endPoint, carType[active], drivingTime, couponInfo, moneyInfo, remark)
        if (!this.verify()) {
            return
        }
        let tis = this
        const orderInfo = {
            order_string: '', //获取两地距离和计算金额接口返回的参数
            order_token: '', //获取两地距离和计算金额接口返回的参数
            start_user_name: startPoint.user.name, //发件人姓名
            end_user_name: endPoint.user.name, //收件人姓名
            start_user_phone: startPoint.user.phone, //发件人电话
            end_user_phone: endPoint.user.phone, //收件人电话
            start_address: startPoint.name + startPoint.location, //发件人地址
            end_address: endPoint.name + endPoint.location, //收件人地址
            coupon_id: couponInfo.id || '', //优惠券ID
            remark: remark, //备注信息 非必填
            car_people: this.data.carType[this.data.active].followingNumber,
            cat_type: this.data.carType[this.data.active].petType,
            order_money: moneyInfo.all_money,
            carInfo: this.data.carType[this.data.active],
            people_num: this.data.flowingNum, //跟车人数
            cat_num: this.data.flowingPet, //宠物数量
            gotime: drivingTime
        }
        console.log(orderInfo, '---orderinfo')

        wx.authorize({
            scope: 'scope.userLocationBackground',
            success: res => {
                console.log('权限获取成功', res)
                wx.startLocationUpdateBackground({
                    success: (res: any) => {
                        console.log('获取位置成功', res)
                        tis.zhifu(orderInfo)
                        wx.onLocationChange(data => {
                            console.log(data)
                        })
                    },
                    fail: res => {
                        console.log('获取位置失败', res)
                        wx.openSetting()
                        tis.weizhi(orderInfo)
                    }
                })
            },
            fail: res => {
                console.log('权限获取失败', res)
                wx.openSetting()
                tis.weizhi(orderInfo)
            }
        })
    }),
    toLocationSelect(e: any) {
        wx.chooseAddress({
            success: async res => {
                if (e.currentTarget.dataset.type === 'start') {
                    this.setData({
                        // @ts-ignore
                        startPoint: {
                            name: `${res.provinceName}${res.cityName}${res.countyName}`,
                            location: res.detailInfo,
                            user: {
                                name: res.userName,
                                phone: res.telNumber
                            }
                        },
                        drivingTime: '请选择用车时间'
                    })
                } else {
                    this.setData({
                        // @ts-ignore
                        endPoint: {
                            name: `${res.provinceName}${res.cityName}${res.countyName}`,
                            location: res.detailInfo,
                            user: {
                                name: res.userName,
                                phone: res.telNumber
                            }
                        },
                        drivingTime: '请选择用车时间'
                    })
                    const { startPoint, endPoint } = this.data
                    // @ts-ignore
                    const data: any = await getDistant(startPoint.name + startPoint.location, endPoint.name + endPoint.location)
                    console.log(data, '----res')
                    this.setData({
                        distance: data[0].distance < 1000 ? '约 ' + data[0].distance + ' m' : '约 ' + data[0].distance / 1000 + ' km',
                        duration: `预计 ${formatTime(data[0].duration)} 后到达`
                    })
                    this.setData({
                        info: this.data.distance + ' ' + this.data.duration
                    })
                }
            },
            fail: err => {
                console.log(err)
            },
            complete: res => {
                console.log(res)
            }
        })
    },
    onVisibleChange() {
        this.setData({
            dialogVisible: !this.data.dialogVisible
        })
    },
    handlePetChange(e: any) {
        const { value } = e.detail

        console.log(value)
        this.setData({
            flowingPet: value
        })
    },
    handleStepperChange(e: any) {
        const { value } = e.detail

        console.log(value)
        this.setData({
            flowingNum: value
        })
    },
    handlerActive(e: any) {
        const index = e.currentTarget.dataset.index
        this.setData({
            active: index,
            drivingTime: '请选择用车时间',
            oldMoney: 0,
            moneyInfo: {},
            coupon: '',
            couponInfo: {},
            flowingNum: 0,
            flowingPet: 1
        })
    },
    showPicker() {
        this.setData({
            datetimeVisible: !this.data.datetimeVisible
        })
    },
    hidePicker() {
        this.setData({
            datetimeVisible: false
        })
    },

    async weizhi(orderInfo: any) {
        let tis = this
        let userLocation = false
        let userLocationBackground = false
        wx.getSetting({
            success: async (ress: any) => {
                for (let i in ress.authSetting) {
                    if (i == 'scope.userLocation' && ress.authSetting[i]) {
                        userLocation = ress.authSetting[i]
                    }
                    if (i == 'scope.userLocationBackground' && ress.authSetting[i]) {
                        userLocationBackground = ress.authSetting[i]
                    }
                }
                console.log(userLocation)
                console.log(userLocationBackground)
                if (userLocation && userLocationBackground) {
                    tis.zhifu(orderInfo)
                } else {
                    wx.showToast({
                        title: '点击右上角设置\r\n开打后台定位',
                        icon: 'error',
                        duration: 2000
                    })
                }
            },
            fail: res => {
                console.log(res)
            }
        })
    },

    async zhifu(orderInfo: any) {
        let rangeRes: any = await GetRangeMoney({
            address1: orderInfo.start_address, //起始地址 字符串类型 2
            address2: orderInfo.end_address, //终止地址 字符串类型 2
            car_id: orderInfo.carInfo.id, //车型ID
            gotime: orderInfo.gotime.split(' ')[1]
        })
        console.log(rangeRes, '---rangeRes')
        console.log(orderInfo)
        orderInfo.order_string = rangeRes[0].order_string
        orderInfo.order_token = rangeRes[0].order_key
        let resc: any = await createOrder(orderInfo)
        if (resc.data.data.length == 0) {
            wx.showToast({
                title: '当前已有订单',
                // @ts-ignore
                icon: 'error',
                duration: 2000
            })
        } else if (resc.data.data[0].errmsg == '优惠券不存在或已被使用!') {
            this.setData({
                coupon: '',
                couponInfo: {},
                moneyInfo: {
                    ...this.data.moneyInfo,
                    all_money: this.data.oldMonrey
                }
            })
        } else {
            const res: any = await payOrder(resc.data.data[0].order_id)
            await wx.requestPayment({
                timeStamp: res[0].timeStamp.toString(),
                nonceStr: res[0].nonce,
                package: res[0].package,
                signType: res[0].signType,
                paySign: res[0].paySign,
                success() {
                    wx.showToast({
                        title: '支付成功',
                        icon: 'success',
                        duration: 1000
                    })
                    wx.redirectTo({
                        url: `/pages/map/map?orderId=${resc.data.data[0].order_id}`
                    })
                },
                fail(res) {
                    console.log(res)
                    wx.showToast({
                        title: '支付失败',
                        icon: 'error',
                        duration: 500
                    })
                }
            })
        }
    },
    async onConfirm(e: any) {
        const { value } = e?.detail
        this.setData({
            drivingTime: value
        })
        if (!this.verify()) {
            this.hidePicker()
            this.setData({
                drivingTime: ''
            })
            return
        }

        const { startPoint, endPoint, active, carType, drivingTime } = this.data
        // @ts-ignore
        const data: any = await getDistantAndMoney(startPoint.name + startPoint.location, endPoint.name + endPoint.location, carType[active].id, drivingTime)
        console.log(data, '----getDistantAndMoney')
        this.setData({
            moneyInfo: data[0],
            oldMoney: data[0].all_money,
            coupon: '',
            couponInfo: {}
        })
        this.hidePicker()
    },

    /**
     * 生命周期函数--监听页面加载
     */ async onLoad() {
        const data: any = await obtainVehicleType()
        let index = 0
        const carType = data.map((item: any) => {
            return {
                index: index++,
                id: item.ID,
                petType: item.cat_type,
                petNum: item.car_people,
                name: item.car_name,
                followingNumber: item.car_cat_people,
                carType: item.Car_Type_Name,
                max: item.car_cat_people
            }
        })
        console.log(carType)
        this.setData({
            carType: carType
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if (Object.keys(this.data.couponInfo).length != 0) {
            const { couponInfo, moneyInfo, oldMoney } = this.data

            if (couponInfo.info.moneyStart > oldMoney) {
                console.log('金额未达到满减')
                wx.showToast({
                    title: '金额未达到满减',
                    // @ts-ignore
                    icon: 'error',
                    duration: 1000
                })
                this.setData({
                    moneyInfo: {
                        ...moneyInfo,
                        all_money: this.data.oldMoney
                    },
                    coupon: '',
                    couponInfo: {}
                })
            } else {
                let money = this.data.oldMoney - couponInfo.info.num
                if (money <= 0) {
                    money = 0
                }
                this.setData({
                    moneyInfo: {
                        ...moneyInfo,
                        all_money: money
                    }
                })
            }
            console.log(this.data.coupon, couponInfo, moneyInfo)
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {}
})
